import {
  fetchUserCenter
} from '../../services/usercenter/fetchUsercenter';
import Toast from 'tdesign-miniprogram/toast/index';

import {
  phoneEncryption,
} from '../../utils/util';

// import {
// 	phoneEncryption,
// } from '../../packageB';
const $api = require('../../utils/request').Api;
const app = getApp()

const menuData = [
  [
    // {
    // 		title: '收货地址',
    // 		tit: '',
    // 		url: '',
    // 		type: 'address',
    // 	},
    // 	{
    // 		title: '优惠券',
    // 		tit: '',
    // 		url: '',
    // 		type: 'coupon',
    // 	},
    // 	{
    // 		title: '卡包',
    // 		tit: '',
    // 		url: '',
    // 		type: 'card',
    // 	},
    // {
    //   title: '积分',
    //   tit: '',
    //   url: '',
    //   type: 'point',
    // },
    // {
    //   title: '每日签到',
    //   tit: '',
    //   url: '',
    //   type: 'attendance',
    // },
    // {
    // 	title: '订单详情',
    // 	tit: '',
    // 	url: '',
    // 	type: 'Orderdetails',
    // },
  ],
  [
    {
      title: '更多服务',
      tit: '',
      url: '',
      type: 'serve',
    },
    {
      title: '帮助中心',
      tit: '',
      url: '',
      type: 'help-center',
    },
    {
      title: '客服热线',
      tit: '',
      url: '',
      type: 'service',
      // icon: 'service',
    },
    {
      title: '加盟我们',
      tit: '',
      url: '',
      type: 'info-circle',
      icon: 'service',
    },
  ],
];

const orderTagInfos = [{
    title: '全部订单',
    iconName: app.globalData.baseImgUrl +'/image/icon1.png',
    orderNum: 0,
    tabType: 5,
    status: 1,
  },
  // {
  //   title: '地址管理',
  //   iconName: app.globalData.baseImgUrl +'/image/icon2.png',
  //   orderNum: 0,
  //   tabType: 10,
  //   status: 1,
  // },
  // {
  // 	title: '优惠券',
  // 	iconName: app.globalData.baseImgUrl +'/image/icon3.png',
  // 	orderNum: 0,
  // 	tabType: 40,
  // 	status: 1,
  // },
// 隐藏积分商城
  // {
  //   title: '积分商城',
  //   iconName: app.globalData.baseImgUrl +'/image/jifenkqifen.png',
  //   orderNum: 0,
  //   tabType: 60,
  //   status: 1,
  // },
  {
    title: '代金券',
    iconName: app.globalData.baseImgUrl +'/image/daijinjuan.png',
    orderNum: 0,
    tabType: 80,
    status: 1,
  },
  {
    title: '礼品卡兑换',
    iconName: app.globalData.baseImgUrl +'/image/lipinka.png',
    orderNum: 0,
    tabType: 90,
    status: 1,
  },
  // {
  // 	title: '退款/售后',
  // 	iconName: '../../../image/icon1.png',
  // 	orderNum: 0,
  // 	tabType: 0,
  // 	status: 1,
  // },
];
const getDefaultData = () => ({
  showMakePhone: false,
  showMakeAbout: false,
  userInfo: {
    avatarUrl: '',
    nickName: '正在登录...',
    phoneNumber: '',
    memberNumber: '',
  },
  menuData,
  orderTagInfos,
  customerServiceInfo: {}, // todo 要有电话信息
  currAuthStep: 1,
  showKefu: true,
  versionNo: '',
  baseImgUrl: app.globalData.baseImgUrl
});
Page({
  data: getDefaultData(),
  onLoad() {
    this.getVersionInfo();

    // this.init()
  },

  onShow() {
    // this.getTabBar().init();
    let login = wx.getStorageSync('login')
    let userTel = wx.getStorageSync('userTel')
    if (login !== '' && login.data !== '' && login.data.code !== 500) {
      console.log('dengdairexie');
      this.setData({
        'userInfo.phoneNumber': phoneEncryption(userTel.data),
        'userInfo.avatarUrl': login.data.data.avatar,
        'userInfo.memberNumber': login.data.data.memberNumber,
        currAuthStep: 2,
      })
    } else {
      // this.init();
      this.setData({
        // 'userInfo.phoneNumber': phoneEncryption(userTel.data),
        currAuthStep: 1,
      })
      wx.navigateTo({ url: '/packageB/pages/usercenter/userAuthorized/Authorized' })
    }

  },
  onPullDownRefresh() {
    // this.init();
  },

  init() {
    this.fetUseriInfoHandle();
  },

  fetUseriInfoHandle() {
    fetchUserCenter().then(
      ({
        userInfo,
        countsData,
        orderTagInfos: orderInfo,
        customerServiceInfo,
      }) => {
        console.log({ customerServiceInfo });
        // eslint-disable-next-line no-unused-expressions
        menuData?.[0].forEach((v) => {
          countsData.forEach((counts) => {
            if (counts.type === v.type) {
              // eslint-disable-next-line no-param-reassign
              v.tit = counts.num;
            }
          });
        });
        const info = orderTagInfos.map((v, index) => ({
          ...v,
          ...orderInfo[index],
        }));
        this.setData({
          userInfo,
          menuData,
          orderTagInfos: info,
          customerServiceInfo,
          currAuthStep: 2,
          // 'userInfo.phoneNumber': phoneEncryption(userInfol.userInfo.phoneNumber),
        });
        wx.stopPullDownRefresh();
      },
    );
  },

  onClickCell({
    currentTarget
  }) {
    const {
      type
    } = currentTarget.dataset;
    console.log(type);
    switch (type) {
      case 'address': {
        wx.navigateTo({
          url: '/packageB/pages/usercenter/address/list/index'
        });
        break;
      }
      case 'service': {
        this.openMakePhone();
        break;
      }
      // case 'help-center': {
      //   Toast({
      //     context: this,
      //     selector: '#t-toast',
      //     message: '你点击了帮助中心',
      //     icon: '',
      //     duration: 1000,
      //   });
      //   break;
      // }
      case 'help-center': {
        wx.navigateTo({
          url: '/pages/HelpCenter/HelpCenter',  // 新页面的路径，根据你的实际情况进行修改
          success: function(res) {
            console.log('跳转到帮助页面成功');
          },
          fail: function(res) {
            console.log('跳转到帮助页面失败', res);
          }
        });
        break;
      }

      // case 'attendance': {
      //   Toast({
      //     context: this,
      //     selector: '#t-toast',
      //     message: '你点击了积分菜单',
      //     icon: '',
      //     duration: 1000,
      //   });
      //   wx.navigateTo({
      //     url: '/pages/Sign/sign'
      //   });
      //   break;
      // }
      case 'point': {
        wx.navigateTo({
          url: '/pages/integralMall/list'
        });
        break;
      }
      case 'coupon': {
        wx.navigateTo({
          url: '/pages/coupon/coupon-list/index'
        });
        break;
      }
      case 'card': {
        wx.navigateTo({
          url: '/pages/goods/Cardpack/cardindex'
        });
        break;
      }
      case 'Orderdetails': {
        wx.navigateTo({
          url: '/pages/goods/Orderdetails/orderindex'
        });
        break;
      }
      // 更多服务 serve
      default: {
        // Toast({
        //   // context: this,
        //   // selector: '#t-toast',
        //   // message: '未知跳转',
        //   icon: '',
        //   duration: 1000,
        // });
        this.openMakeAbout()
        break;
      }
    }
  },

  jumpNav(e) {
    const status = e.detail.tabType;
    console.log(e);
    if (status === 0) {
      // 积分商城
      // wx.navigateTo({
      // 	url: '/pages/order/after-service-list/index'
      // });

      Toast({
        context: this,
        selector: '#t-toast',
        message: '你点击了积分菜单',
        icon: '',
        duration: 1000,
      });
      wx.navigateTo({
        url: '/pages/Sign/sign'
      });
    } else if (status === 5) {
      // wx.navigateTo({
      // 	url: `/pages/order/order-list/index`
      // });
      wx.navigateTo({
        url: '/pages/goods/Orderdetails/orderindex'
      });
    } else if (status === 10) {
      wx.navigateTo({
        url: `/pages/usercenter/address/list/index`
      });
    } else if (status === 40) {
      // 优惠卷 40
      wx.navigateTo({
        url: '/pages/coupon/coupon-list/index'
      });
    } else if (status === 80) {
      // 优惠卷 40
      wx.navigateTo({
        url: '/pages/voucher/voucher'
      });
    } else {
      wx.navigateTo({
        url: `/pages/giftCard/index`,
      });
      // wx.navigateTo({
      //   url: `/pages/order/order-list/index?status=${status}`
      // });
    }
  },

  jumpAllOrder() {
    wx.navigateTo({
      url: '/pages/order/order-list/index'
    });
  },

  openMakePhone() {
    this.setData({
      showMakePhone: true
    });
  },

  closeMakePhone() {
    this.setData({
      showMakePhone: false
    });
  },
  openMakeAbout() {
    this.setData({
      showMakeAbout: true
    });
  },

  closeMakeAbout() {
    this.setData({
      showMakeAbout: false
    });
  },

  call() {
    wx.makePhoneCall({
      phoneNumber: '010-53658000'
    });
  },

  gotoUserEditPage() {
    // let user = wx.setStorageSync('user', user)
    const login = wx.getStorageSync('login')
    // const {
    //   currAuthStep
    // } = this.data;
    // if (currAuthStep === 2) {

    if (login === '' || login.data.code === 500) {
      wx.navigateTo({
        url: '/packageB/pages/usercenter/userAuthorized/Authorized'
      });
    } else {
      this.updateUserAvatar()
      // wx.navigateTo({
      // 	url: '/pages/usercenter/person-info/index'
      // });
    }
    // } else {
    //   this.fetUseriInfoHandle();
    // }
  },
  updateUserAvatar () {
    wx.chooseImage({
      count: 1,
      sourceType: ['album'],
      success: ({ tempFilePaths: [file] }) => {
        wx.uploadFile({
          url: app.globalData.baseApiUrl +'/api/upload/uploadFile', // 仅为示例，非真实的接口地址
          filePath: file,
          name: 'file',
          // formData: { user: 'test' },
          success: ({ data: result }) => {
            const avatar = JSON.parse(result).uploadUrl
            this.setData({ 'userInfo.avatarUrl': avatar })
            const login = wx.getStorageSync('login')
            login.data.data.avatar = avatar
            wx.setStorageSync('login', login)
            $api.headPortrait({
              memberNumber: login.data.data.memberNumber,
              headPortrait: avatar,
            })
          },
          fail: () => {
            wx.showToast({ title: '更换失败', icon: 'none' })
          }
        })
      }
    })
  },
  getVersionInfo() {
    const versionInfo = wx.getAccountInfoSync();
    const {
      version,
      envVersion = __wxConfig
    } = versionInfo.miniProgram;
    this.setData({
      versionNo: envVersion === 'release' ? version : envVersion,
    });
  },
  scan: function (e) {
    console.log(e);
    let that = this;
    // //app.showError("功能开发中，敬请期待！");

    wx.scanCode({
      success: (res) => {
        // console.log(res.path.split('?')[1]);
        let add = res.path.split('?')[1]
        let arr = add[1]
        console.log(arr);
        //https://dl.lxcx365.com/index.php?m=Goods&a=g_list&m_id=1&mas_id=10&b_id=1&sort=1&type=breakfast

        // if (that.getUrlParam(res.result, "type") == "breakfast") {
        // 	var mId = that.getUrlParam(res.result, "m_id"),
        // 		masId = that.getUrlParam(res.result, "mas_id"),
        // 		bId = that.getUrlParam(res.result, "b_id"),
        // 		sort = that.getUrlParam(res.result, "sort");

        // if(that.data.isOrder){
        //     //有预约订单
        //     wx.navigateTo({
        //         url: '../breakfast/orderList?sort=' + sort + '&isBreakfirst=' + that.data.isBreakfirst,
        //     });
        // }else{
        //     //无预约订单
        //     if(!that.data.isBreakfirst || that.data.Breakfirst.button_sx == 2){
        //         // 未开启现场点餐
        //         app.showError("您还没有预约订单");
        //     }
        //     if(that.data.isBreakfirst && that.data.Breakfirst.button_sx == 1){
        // 已开启现场点餐
        wx.navigateTo({
          url: '/packageA/pages/Shophomepage/index?' + res.path.split('?')[1],
        });
        //     }
        // }

        // } else {
        // 	// res.result = "https://more.octopus.cn/now/order?a=58&p=35&td_channelid=31&uuid=36a15004525b550a16b410060b43e5f&va=1560163672";
        // 	//存入本地存储
        // 	wx.setStorage({
        // 		key: 'zyOder',
        // 		data: res.result
        // 	});

        // 	wx.navigateTo({
        // 		url: '../OutZy/out',
        // 	});
        // }
      }
    });
    // wx.navigateTo({
    //     // url: '../breakfast/index',
    //     // url: '../breakfast/appointment',
    //     // url: '../breakfast/orderList',
    //     url: '../breakfast/index?m_id=1&mas_id=10&b_id=1&sort=2',
    //     // url: '../groupWeek/index',
    //     // url: '../group/index',
    // });
  },
});
